package com.xiaohong.pay.AliPay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.xiaohong.order.feign.OrderFeign;
import com.xiaohong.order.feign.OrderItemFeign;
import com.xiaohong.order.pojo.Order;
import com.xiaohong.order.pojo.OrderItem;
import com.xiaohong.pay.AliPay.interceptor.TokenRequestInterceptor;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author xiaohong
 * @Description
 * @date 2020/12/23 0023 21:33
 */
@Controller
@RequestMapping("/zfbPay")
public class ZfbPayController {


    @Value("${zfb.app_id}")
    private String app_id;

    @Value("${zfb.gatewayUrl}")
    private String gatewayUrl;

    @Value("${zfb.merchant_private_key}")
    private String merchant_private_key;

    @Value("${zfb.alipay_public_key}")
    private String alipay_public_key;

    @Value("${zfb.sign_type}")
    private String sign_type;

    @Value("${zfb.charset}")
    private String charset;

    @Value("${zfb.return_url}")
    private String return_url;

    @Value("${zfb.notify_url}")
    private String notify_url;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private OrderItemFeign orderItemFeign;


    /**
     * 支付宝支付页面跳转
     * @param sn
     * @param token
     * @return
     */
    @GetMapping("pay")
    public String zfb_pay (
            @RequestParam(value = "sn") String sn,
            @RequestParam(value = "token") String token,
            Model model) {

        TokenRequestInterceptor.token = "Bearer "+token;

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json",charset, alipay_public_key, sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        String html = "订单信息有误！";

        // 获取订单
        Order order = orderFeign.findById(sn).getData();

        if (order != null){
            //请求
            try {
                Map<String, Object> map = new HashMap<>();
                //商户订单号，商户网站订单系统中唯一订单号，必填
                map.put("out_trade_no",sn);
                //付款金额，必填
                map.put("total_amount",order.getPayMoney()+"");
                // 销售产品码，与支付宝签约的产品码名称。 必填
                //注：目前仅支持FAST_INSTANT_TRADE_PAY
                map.put("product_code","FAST_INSTANT_TRADE_PAY");
                //订单名称，必填
                map.put("subject",order.getId());
                // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d 可空
                map.put("timeout_express","10m");
                alipayRequest.setBizContent(JSON.toJSONString(map));
                html = alipayClient.pageExecute(alipayRequest).getBody();
                model.addAttribute("html",html);
                return "/zfb/pay";
            } catch (AlipayApiException e) {
                html = "服务器内部错误！";
                e.printStackTrace();
                model.addAttribute("html",html);
                return "/zfb/pay";
            }
        }



//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//                + "\"total_amount\":\""+ total_amount +"\","
//                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节



        // 清空token
        TokenRequestInterceptor.token = null;

        model.addAttribute("html",html);
        return "/zfb/pay";
    }

    @RequestMapping("test")
    public void test(HttpServletRequest httpServletRequest) {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = httpServletRequest.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(httpServletRequest.getParameter("out_trade_no"));

            //支付宝交易号
            String trade_no = new String(httpServletRequest.getParameter("trade_no"));

            //付款金额
            String total_amount = new String(httpServletRequest.getParameter("total_amount"));

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
        }else {
            System.out.println("验签失败");
        }
        //——请在这里编写您的程序（以上代码仅作参考）——
        System.out.println("支付宝页面跳转请求方法："+httpServletRequest.getMethod());
        System.out.println("支付宝页面跳转");
    }

    /**
     * 支付宝支付信息回调(只有支付成功才会调用)
     * @param httpServletRequest
     */
    @PostMapping("notify")
    public void zfb_notify(HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = httpServletRequest.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(httpServletRequest.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(httpServletRequest.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(httpServletRequest.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String pay_money = new String(httpServletRequest.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            // 订单名称（id）
            String id = new String(httpServletRequest.getParameter("subject").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println(out_trade_no);
            System.out.println(trade_no);
            System.out.println(pay_money);
            System.out.println(id);

            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //如果有做过处理，不执行商户的业务程序
            //注意：
            //支付宝只在付款成功后，才发送该交易状态通知
            Order order = orderFeign.findById(out_trade_no).getData();
            if (order != null && order.getPayMoney().equals(Float.valueOf(pay_money)) && id.equals(out_trade_no)) {
                // 修改订单状态
                Order order1 = new Order();
                order1.setTransactionId(trade_no);
                order1.setPayStatus(1);
                orderFeign.update(order1, out_trade_no);
                // 修改子订单状态
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(out_trade_no);
                List<OrderItem> data = orderItemFeign.findList(orderItem).getData();
                for (OrderItem datum : data) {
                    OrderItem orderItem1 = new OrderItem();
                    orderItem1.setStatus(1);
                    orderItemFeign.update(orderItem1, datum.getId());
                }
            }
        }
    }

}
